package org.jeecg.modules.travel.carpool.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.jeecg.common.api.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import org.jeecg.modules.travel.carpool.entity.TravelCarpool;
import org.jeecg.modules.travel.carpool.entity.TravelJourney;
import org.jeecg.modules.travel.user.entity.TravelWechatUser;
import org.jeecg.modules.travel.user.entity.TravelDrivers;
import org.jeecg.modules.travel.user.entity.TravelStudents;

import org.jeecg.modules.travel.carpool.mapper.TravelCarpoolMapper;
import org.jeecg.modules.travel.carpool.mapper.TravelJourneyMapper;
import org.jeecg.modules.travel.user.mapper.TravelDriversMapper;
import org.jeecg.modules.travel.user.mapper.TravelStudentsMapper;
import org.jeecg.modules.travel.user.mapper.TravelWechatUserMapper;

import org.jeecg.modules.travel.carpool.service.ITravelCarpoolService;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: jeecg 测试demo
 * @Author: jeecg-boot
 * @Date:  2018-12-29
 * @Version: V1.0
 */
@Service
public class TravelCarpoolImpl extends ServiceImpl<TravelCarpoolMapper, TravelCarpool> implements ITravelCarpoolService {
	@Autowired
	TravelCarpoolMapper travelCarpoolMapper;
	@Autowired
	TravelJourneyMapper travelJourneyMapper;
	@Autowired
	TravelDriversMapper travelDriversMapper;
	@Autowired
	TravelStudentsMapper travelStudentsMapper;
	@Autowired
    TravelWechatUserMapper travelWechatUserMapper;

	
    @Transactional
    public Result<String> createTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        TravelCarpool tcp = new TravelCarpool();
        tcp.setUid(sysUser.getId());
        // 从 TravelWechatUser 表中获取当前登录人的信息
        QueryWrapper<TravelWechatUser> quw = new QueryWrapper<>();
        quw.eq("sys_uid", sysUser.getId());
        TravelWechatUser user = travelWechatUserMapper.selectOne(quw);
        if(user == null){
            res.setSuccess(false);
            res.setMessage("当前用户不存在");
            return res;
        }
        //价格不能小于1
        if( data.getDouble("price") < 1 ){
            res.setSuccess(false);
            res.setMessage("价格不能小于1");
            return res;
        }
        tcp.setPrice(data.getDouble("price"));
        tcp.setRemark(data.getString("remark"));
        tcp.setName(user.getName());
        tcp.setPhone(user.getPhone());
        tcp.setAvatarUrl(user.getAvatarUrl());
        tcp.setDriver(data.getBoolean("driver"));
        tcp.setPlanTime(data.getDate("plan_time"));
        tcp.setStartingName(data.getString("starting_name"));
        tcp.setStartingPoint(data.getString("starting_point"));
        tcp.setEndName(data.getString("end_name"));
        tcp.setEndPoint(data.getString("end_point"));
        tcp.setStatus(1);
        tcp.setEmptySeat(0);
        if( tcp.getDriver() ){
            //// 判断 TravelDrivers 表中是否存在条件符合的数据 条件是 uid=当前登录人的id
            QueryWrapper<TravelDrivers> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", sysUser.getId());
            TravelDrivers driver = travelDriversMapper.selectOne(queryWrapper);
            if(driver == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                res.setSuccess(false);
                res.setMessage("当前用户不是司机，无法发布车找人行程");
                return res;
            }
            tcp.setEmptySeat(driver.getSeating());
            tcp.setIid(driver.getId().toString());
        }else if( data.getJSONArray("iid") != null ){
            // 判断 TravelStudents 表中是否存在条件符合的数据 条件是 uid=当前登录人的id id=tcp.iid
            List<Integer> iids = data.getJSONArray("iid").toJavaList(Integer.class);
            for (Integer iid : iids) {
                QueryWrapper<TravelStudents> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("uid", sysUser.getId());
                queryWrapper.eq("id", iid);
                TravelStudents student = travelStudentsMapper.selectOne(queryWrapper);
                if(student == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    res.setSuccess(false);
                    res.setMessage("指定的学生不属于当前用户，无法发布行程");
                    return res;
                }
            }
            if( iids.size() > 0 ){
                tcp.setIid(iids.stream().map(Object::toString).collect(Collectors.joining(",")));
            }
        }
        int ret =  travelCarpoolMapper.insert(tcp);
        if( ret > 0){
            res.setSuccess(true);
            res.setMessage("发布行程成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.setSuccess(false);
            res.setMessage("发布行程失败");
        }
		return res;
    }

    /**
     * 关闭行程
     * @param data
     * @return
     */
    @Transactional
    public Result<String> closeTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //获取行程信息
        TravelCarpool tcp = travelCarpoolMapper.selectById(data.getLong("id"));
        if(tcp == null){
            res.setSuccess(false);
            res.setMessage("该行程不存在");
            return res;
        }
        if( !tcp.getUid().equals(sysUser.getId()) ){
            res.setSuccess(false);
            res.setMessage("没有权限操作！");
            return res;
        }
        if(tcp.getStatus() != 1){
            res.setSuccess(false);
            res.setMessage("该行程当前状态，无法关闭");
            return res;
        }

        // 关闭所有关联的 TravelJourney 表中的数据
        QueryWrapper<TravelJourney> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid", tcp.getId());
        queryWrapper.in("status",0,2);
        TravelJourney tj = new TravelJourney();
        tj.setStatus(1);
        tj.setFinishTime(new Date());
        travelJourneyMapper.update(tj, queryWrapper);

        tcp.setStatus(0);
        tcp.setFinishTime(new Date());
        int ret =  travelCarpoolMapper.updateById(tcp);
        if( ret > 0){
            res.setSuccess(true);
            res.setMessage("关闭行程成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.setSuccess(false);
            res.setMessage("关闭行程失败");
        }
        return res;
    }


    @Transactional
    public Result<String> joinTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();


        //获取行程信息
        TravelCarpool tcp = travelCarpoolMapper.selectById(data.getLong("cid"));
        if(tcp == null){
            res.setSuccess(false);
            res.setMessage("该行程不存在");
            return res;
        }
        if(tcp.getUid().equals(sysUser.getId())){
            res.setSuccess(false);
            res.setMessage("不能加入自己发布的行程");
            return res;
        }
        if(tcp.getStatus() != 1){
            res.setSuccess(false);
            res.setMessage("该行程已经结束，无法加入");
            return res;
        }

        // 从 TravelWechatUser 表中获取当前登录人的信息
        QueryWrapper<TravelWechatUser> quw = new QueryWrapper<>();
        quw.eq("sys_uid", sysUser.getId());
        TravelWechatUser user = travelWechatUserMapper.selectOne(quw);
        if(user == null){
            res.setSuccess(false);
            res.setMessage("当前用户不存在");
            return res;
        }

        //创建行程申请单
        TravelJourney tj = new TravelJourney();
        tj.setCid(tcp.getId());
        tj.setSeat(1);
        if(tcp.getDriver()){
            //获取司机信息
            TravelDrivers driver = travelDriversMapper.selectById(tcp.getIid());
            if(driver == null){
                res.setSuccess(false);
                res.setMessage("该行程的司机信息不存在");
                return res;
            }
            //判断是否已经有人加入
            QueryWrapper<TravelJourney> tw  = new QueryWrapper<TravelJourney>().eq("cid", data.getLong("id"));
            tw.eq("status", 2);
            tw.select("sum(seat) as seat");
            TravelJourney t = travelJourneyMapper.selectOne(tw);
            int tcount = 0;
            if(t != null){
                tcount = t.getSeat();
            }
            if(tcount >= driver.getSeating()){
                res.setSuccess(false);
                res.setMessage("该行程已经满员，无法再加入");
                return res;
            }

            //获取学生信息
            List<Integer> sids = data.getJSONArray("sid").toJavaList(Integer.class);
            if(sids.size() > 0){
                if(sids.size() > driver.getSeating() - tcount){
                    res.setSuccess(false);
                    res.setMessage("该行程剩余座位不足，无法加入");
                    return res;
                }
                for (Integer sid : sids) {
                    QueryWrapper<TravelStudents> sw = new QueryWrapper<TravelStudents>().eq("uid", sysUser.getId());
                    sw.eq("id", sid);
                    if( ! travelStudentsMapper.exists(sw )  ) {
                        res.setSuccess(false);
                        res.setMessage("指定的学生不属于当前用户，无法加入行程");
                        return res;
                    }
                }
                tj.setSid(sids.stream().map(Object::toString).collect(Collectors.joining(",")));
                tj.setSeat(sids.size());
            }
            tj.setDriver(false);
        }else{
            tj.setDriver(true);
            TravelDrivers tdi = travelDriversMapper.selectOne(new QueryWrapper<TravelDrivers>().eq("uid", sysUser.getId()));
            if(tdi == null){
                res.setSuccess(false);
                res.setMessage("当前用户不是司机，无法加入车找人行程");
                return res;
            }
            tj.setSid(tdi.getId().toString());
        }
        tj.setUid(sysUser.getId());
        tj.setName(user.getName());
        tj.setPhone(user.getPhone());
        tj.setAvatarUrl(user.getAvatarUrl());
        tj.setStatus(0);
        // 插入行程申请单
        int ret =  travelJourneyMapper.insert(tj);
        if( ret > 0){
            res.setSuccess(true);
            res.setMessage("加入行程成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.setSuccess(false);
            res.setMessage("加入行程失败");
        }
		return res;
    }

    
    //关闭申请加入行程
    public Result<String> closeJoinTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取行程信息
        QueryWrapper<TravelJourney> jw = new QueryWrapper<>();
        jw.eq("uid", sysUser.getId());
        jw.eq("id", data.getLong("id"));
        TravelJourney tcp = travelJourneyMapper.selectOne(jw);
        if(tcp == null){
            res.setSuccess(false);
            res.setMessage("您没有权限操作");
            return res;
        }
        if(tcp.getStatus() != 0 && tcp.getStatus() != 2){
            res.setSuccess(false);
            res.setMessage("该行程状态，无法关闭");
            return res;
        }
        tcp.setFinishTime(new Date());
        tcp.setStatus(1);
        int ret =  travelJourneyMapper.updateById(tcp);
        if( ret > 0){
            res.setSuccess(true);
            res.setMessage("关闭行程成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.setSuccess(false);
            res.setMessage("关闭行程失败");
        }
        return res;
    }

    /**
     * 审核加入行程
     * @param data
     * @return
     */
    @Transactional
    public Result<String> checkJoinTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取行程信息
        TravelJourney tcp = travelJourneyMapper.selectById(data.getLong("id"));
        if(tcp == null){
            res.setSuccess(false);
            res.setMessage("该申请不存在");
            return res;
        }

        if(tcp.getStatus() != 0){
            res.setSuccess(false);
            res.setMessage("该申请当前状态，无法审核");
            return res;
        }

        QueryWrapper<TravelCarpool> cw = new QueryWrapper<TravelCarpool>();
        cw.eq("id", tcp.getCid());
        cw.eq("uid", sysUser.getId());
        cw.eq("status", 1);
        TravelCarpool ci = travelCarpoolMapper.selectOne(cw);
        if(ci == null){
            res.setSuccess(false);
            res.setMessage("您没有权限操作");
            return res;
        }

        if( ci.getDriver() ){
            //判断是否已经有人加入
            if(  ci.getEmptySeat() <= 0 ){
                res.setSuccess(false);
                res.setMessage("该行程已经满员，无法再加入");
                return res;
            }
            //判断空位是否足够
            if( tcp.getSeat() > ci.getEmptySeat() ){
                res.setSuccess(false);
                res.setMessage("该行程空位不满足当前申请，无法加入");
                return res;
            }
            ci.setEmptySeat( ci.getEmptySeat() - tcp.getSeat() );
            travelCarpoolMapper.updateById(ci);
        }

        if(data.getInteger("status") == 1){
            tcp.setStatus(2);
        }else{
            tcp.setStatus(1);
        }

        int ret =  travelJourneyMapper.updateById(tcp);
        if( ret > 0){
            res.setSuccess(true);
            res.setMessage("审核行程成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            res.setSuccess(false);
            res.setMessage("审核行程失败");
        }
        return res;
    }

    /**
     * 开始行程
     * @param data
     * @return
     */
    @Transactional
    public Result<String> startTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        int type = data.getInteger("type");
        if(type == 1){
            //获取行程信息
            QueryWrapper<TravelJourney> jw = new QueryWrapper<>();
            jw.eq("uid", sysUser.getId());
            jw.eq("id", data.getLong("id"));
            TravelJourney tcp = travelJourneyMapper.selectOne(jw);
            if(tcp == null){
                res.setSuccess(false);
                res.setMessage("没有权限或无法操作");
                return res;
            }

            if(tcp.getStatus() != 2){
                res.setSuccess(false);
                res.setMessage("该申请当前状态，无法开始");
                return res;
            }

            QueryWrapper<TravelCarpool> cw = new QueryWrapper<TravelCarpool>();
            cw.eq("id", tcp.getCid());
            cw.eq("status", 1);
            TravelCarpool ci = travelCarpoolMapper.selectOne(cw);
            if(ci == null){
                res.setSuccess(false);
                res.setMessage("行程状态错误，无法开始。");
                return res;
            }

            ci.setStatus(2);
            ci.setStartTime(new Date());
            int ret =  travelCarpoolMapper.updateById(ci);

            tcp.setStatus(3);
            tcp.setStartPoint(data.getString("pos"));
            tcp.setStartTime(new Date());
            int retb =  travelJourneyMapper.updateById(tcp);
            if( ret > 0 && retb > 0){
                res.setSuccess(true);
                res.setMessage("开始行程成功");
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                res.setSuccess(false);
                res.setMessage("开始行程失败");
            }
        }else{
            //获取行程信息
            QueryWrapper<TravelCarpool> cw = new QueryWrapper<TravelCarpool>();
            cw.eq("id", data.getLong("id"));
            cw.eq("uid", sysUser.getId());
            TravelCarpool tc = travelCarpoolMapper.selectOne(cw);
            if(tc == null){
                res.setSuccess(false);
                res.setMessage("没有权限或无法操作");
                return res;
            }
            if(tc.getStatus() != 1){
                res.setSuccess(false);
                res.setMessage("该申请当前状态，无法开始");
                return res;
            }
            tc.setStatus(2);
            tc.setStartTime(new Date());
            int ret =  travelCarpoolMapper.updateById(tc);

            QueryWrapper<TravelJourney> jw = new QueryWrapper<>();
            jw.eq("cid", data.getLong("id"));
            jw.eq("status", 2);
            TravelJourney tj = new TravelJourney();
            tj.setStatus(3);
            tj.setStartTime(new Date());
            tj.setStartPoint(data.getString("pos"));
            int retb =  travelJourneyMapper.update(tj, jw);
            if( ret > 0){
                res.setSuccess(true);
                res.setMessage("开始行程成功");
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                res.setSuccess(false);
                res.setMessage("开始行程失败");
            }
        }
        return res;
    }

    /**
     * 完成行程
     * @param data
     * @return
     */
    @Transactional
    public Result<String> finishTravel(JSONObject data) {
        Result<String> res = new Result<String>();
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        int type = data.getInteger("type");
        if(type == 1){
            //获取行程信息
            QueryWrapper<TravelJourney> jw = new QueryWrapper<>();
            jw.eq("uid", sysUser.getId());
            jw.eq("id", data.getLong("id"));
            TravelJourney tcp = travelJourneyMapper.selectOne(jw);
            if(tcp == null){
                res.setSuccess(false);
                res.setMessage("没有权限或无法操作");
                return res;
            }

            if(tcp.getStatus() != 3){
                res.setSuccess(false);
                res.setMessage("该申请当前状态，无法结束");
                return res;
            }

            QueryWrapper<TravelCarpool> cw = new QueryWrapper<TravelCarpool>();
            cw.eq("id", tcp.getCid());
            cw.eq("status", 2);
            TravelCarpool ci = travelCarpoolMapper.selectOne(cw);
            if(ci == null){
                res.setSuccess(false);
                res.setMessage("行程状态错误，无法结束。");
                return res;
            }

            ci.setStatus(3);
            ci.setFinishTime(new Date());
            int ret =  travelCarpoolMapper.updateById(ci);

            tcp.setStatus(4);
            tcp.setEndPoint(data.getString("pos"));
            tcp.setImages(data.getString("images"));
            tcp.setFinishTime(new Date());
            int retb =  travelJourneyMapper.updateById(tcp);
            if( ret > 0 && retb > 0){
                res.setSuccess(true);
                res.setMessage("结束行程成功");
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                res.setSuccess(false);
                res.setMessage("结束行程失败");
            }
        }else{
            //获取行程信息
            QueryWrapper<TravelCarpool> cw = new QueryWrapper<TravelCarpool>();
            cw.eq("id", data.getLong("id"));
            cw.eq("uid", sysUser.getId());
            TravelCarpool tc = travelCarpoolMapper.selectOne(cw);
            if(tc == null){
                res.setSuccess(false);
                res.setMessage("没有权限或无法操作");
                return res;
            }
            if(tc.getStatus() != 2){
                res.setSuccess(false);
                res.setMessage("该申请当前状态，无法结束");
                return res;
            }
            tc.setStatus(3);
            tc.setFinishTime(new Date());
            int ret =  travelCarpoolMapper.updateById(tc);

            QueryWrapper<TravelJourney> jw = new QueryWrapper<>();
            jw.eq("cid", data.getLong("id"));
            jw.eq("status", 3);
            TravelJourney tj = new TravelJourney();
            tj.setStatus(4);
            tj.setFinishTime(new Date());
            tj.setEndPoint(data.getString("pos"));
            tj.setImages(data.getString("images"));
            int retb =  travelJourneyMapper.update(tj, jw);
            if( ret > 0 && retb > 0 ){
                res.setSuccess(true);
                res.setMessage("行程已完成");
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                res.setSuccess(false);
                res.setMessage("行程完成失败");
            }
        }
        return res;

    }




}
